

using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

#if UNITY_WEBGL && !UNITY_EDITOR
using WeChatWASM;
#endif


/// <summary>
/// 微信输入适配，用于inputfield拉起输入法
/// </summary>
public class WxInputs : MonoBehaviour, IPointerClickHandler, IPointerExitHandler
{
    public TMP_InputField input;
    private bool isShowKeyboad = false;
    // 文本可以输入的最大长度
    public int maxLength = 20;
    
    public void OnPointerClick(PointerEventData eventData)
    {
#if UNITY_WEBGL && !UNITY_EDITOR
        ShowKeyboad();
#endif
    }


    public void OnPointerExit(PointerEventData eventData)
    {
#if UNITY_WEBGL && !UNITY_EDITOR
        // 隐藏输入法
        if (!input.isFocused)
        {
            HideKeyboad();
        }
#endif
    }

#if UNITY_WEBGL && !UNITY_EDITOR
    public void OnInput(OnKeyboardInputListenerResult v)
    {
        Debug.Log("onInput");
        Debug.Log(v.value);
        if (input.isFocused)
        {
            input.text = v.value;
        }
    }

    public void OnConfirm(OnKeyboardInputListenerResult v)
    {
        // 输入法confirm回调
        Debug.Log("onConfirm");
        Debug.Log(v.value);
        HideKeyboad();
    }

    public void OnComplete(OnKeyboardInputListenerResult v)
    {
        // 输入法complete回调
        Debug.Log("OnComplete");
        Debug.Log(v.value);
        HideKeyboad();
    }

    private void ShowKeyboad()
    {

        if (!isShowKeyboad)
        {
            var text = "";
            if (input != null)
            {
                text = input.text;
            }
            WX.ShowKeyboard(new ShowKeyboardOption()
            {
                defaultValue = text,
                maxLength = maxLength,
                confirmType = "go"
            });

            //绑定回调
            WX.OnKeyboardConfirm(OnConfirm);
            WX.OnKeyboardComplete(OnComplete);
            WX.OnKeyboardInput(OnInput);
            isShowKeyboad = true;
        }
    }

    private void HideKeyboad()
    {
        if (isShowKeyboad)
        {
            WX.HideKeyboard(new HideKeyboardOption());
            //删除掉相关事件监听
            WX.OffKeyboardInput(OnInput);
            WX.OffKeyboardConfirm(OnConfirm);
            WX.OffKeyboardComplete(OnComplete);
            isShowKeyboad = false;
        }
    }
#endif
}

